package com.jz.community.moduleshoppingguide.neighbor.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.jakewharton.rxbinding2.view.RxView;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.callback.LoadingCallback;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.neighbor.bean.CircleMessageBean;
import com.jz.community.moduleshoppingguide.neighbor.presenter.NeighborMsgPresenter;
import com.jz.community.moduleshoppingguide.neighbor.ui.NeighborMsgView;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;

public class NeighborMessageActivity extends BaseMvpActivity<NeighborMsgView.View, NeighborMsgPresenter> implements NeighborMsgView.View {

    @BindView(R2.id.circle_message_back)
    ImageView circleMessageBack;
    @BindView(R2.id.circle_message_title)
    TextView circleMessageTitle;
    @BindView(R2.id.circle_message_toolbar)
    Toolbar circleMessageToolbar;
    @BindView(R2.id.circle_message_name_tv)
    TextView circleMessageNameTv;
    @BindView(R2.id.circle_message_name)
    TextView circleMessageName;
    @BindView(R2.id.circle_message_name_rl)
    RelativeLayout circleMessageNameRl;
    @BindView(R2.id.circle_message_name_line)
    ImageView circleMessageNameLine;
    @BindView(R2.id.circle_message_address_tv)
    TextView circleMessageAddressTv;
    @BindView(R2.id.circle_message_address)
    TextView circleMessageAddress;
    @BindView(R2.id.circle_message_address_rl)
    RelativeLayout circleMessageAddressRl;
    @BindView(R2.id.circle_message_address_line)
    ImageView circleMessageAddressLine;
    @BindView(R2.id.circle_message_distance)
    TextView circleMessageDistance;
    @BindView(R2.id.circle_message_distance_rl)
    RelativeLayout circleMessageDistanceRl;
    @BindView(R2.id.circle_message_distance_line)
    ImageView circleMessageDistanceLine;
    @BindView(R2.id.circle_message_user)
    TextView circleMessageUser;
    @BindView(R2.id.circle_message_user_arrow)
    ImageView circleMessageUserArrow;
    @BindView(R2.id.circle_message_user_rl)
    RelativeLayout circleMessageUserRl;
    @BindView(R2.id.circle_message_user_line)
    ImageView circleMessageUserLine;
    @BindView(R2.id.circle_message_dynamic_iv3)
    ImageView circleMessageDynamicIv3;
    @BindView(R2.id.circle_message_dynamic_iv2)
    ImageView circleMessageDynamicIv2;
    @BindView(R2.id.circle_message_dynamic_iv1)
    ImageView circleMessageDynamicIv1;
    @BindView(R2.id.circle_message_dynamic_arrow)
    ImageView circleMessageDynamicArrow;
    @BindView(R2.id.circle_message_dynamic_rl)
    RelativeLayout circleMessageDynamicRl;
    @BindView(R2.id.circle_message_btn)
    TextView circleMessageBtn;
    @BindView(R2.id.circle_message_parent)
    RelativeLayout circleMessageParent;

    private LoadService loadService;
    private String circleId = "";
    /**
     * 是否加入圈子
     */
    private int hasCircle = 0;
    /**
     * 用户是否在当前圈子
     */
    private int isInThisCircle = -1;

    private String circleName;
    private String circlePersons;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_shoppingguide_activity_neighbor_message;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected NeighborMsgPresenter createPresenter() {
        return new NeighborMsgPresenter(this);
    }

    @Override
    protected void initView() {
        super.initView();
        //当白色背景状态栏遇到不能改变状态栏字体为深色的设备时，解决方案
        ImmersionBar
                .with(this)
                .titleBar(circleMessageToolbar)
                .statusBarDarkFont(true, 0.2f)
                .init();

        circleMessageTitle.setText("圈子资料");

        circleId = getIntent().getStringExtra("circle_id");

        loadService = LoadSir.getDefault().register(circleMessageParent, (Callback.OnReloadListener) v -> {
            if (loadService.getCurrentCallback() == ErrorCallback.class) {
                loadService.showCallback(LoadingCallback.class);
                String comLat = BaseSpUtils.getInstance().getCurrentCommuity(mActivity).lat;
                String comLon = BaseSpUtils.getInstance().getCurrentCommuity(mActivity).lon;
                mPresenter.initNeighborMsg(circleId, comLat, comLon);
            }

        });

        loadService.setCallBack(ErrorCallback.class, (context, view) -> {
            ImageView mIvError = (ImageView) view.findViewById(R.id.error_img);
            mIvError.setImageResource(R.mipmap.error_default);

        });

        loadService.setCallBack(LoadingCallback.class, (context, view) -> {
            ImageView mIvLoading = (ImageView) view.findViewById(R.id.loading_img);
            GlideApp.with(mActivity)
                    .asGif()
                    .load(R.drawable.loading_default)
                    .into(mIvLoading);

        });
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initDatas() {
        super.initDatas();
        String comLat = BaseSpUtils.getInstance().getCurrentCommuity(mActivity).lat;
        String comLon = BaseSpUtils.getInstance().getCurrentCommuity(mActivity).lon;
        mPresenter.initNeighborMsg(circleId, comLat, comLon);
        mPresenter.initUserNeighbor();

        hasCircle = BaseSpUtils.getInstance().getCircleStatus(mActivity);

        RxView.clicks(circleMessageBtn)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    //加入或退出圈子
                    if (hasCircle == 0) {
                        //未加入圈子----点击加入圈子
                        mPresenter.addNeighbor(circleId);
                    } else if (hasCircle == 1) {
                        //已加入圈子
                        if (isInThisCircle == 0) {
                            //圈子不是当前圈子
                            showNormal("你已经加入了一个圈子，目前仅允许加入一个圈子。需要加入新圈子，请先退出");
                        } else if (isInThisCircle == 1) {
                            //圈子是当前圈子--退出圈子
                            mPresenter.quitNeighbor(circleId);

                        }
                    }

                });
    }

    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBus(AppEvent message) {
        if (message.tag == EventConfig.REFRESH_CIRCLE_MESSAGE) {
            mPresenter.initUserNeighbor();
        }

    }

    @Override
    public void isAddCircle(CircleMessageBean entity) {
        circleMessageBtn.setVisibility(View.VISIBLE);

        String cId = entity.getId();
        if (cId.equals(circleId)) {
            //如果两个ID相等，用户在当前圈子
            circleMessageBtn.setText("退出圈子");
            isInThisCircle = 1;
        } else {
            //如果两个ID不相等，用户不在当前圈子
            isInThisCircle = 0;
            circleMessageBtn.setText("加入圈子");

        }

        BaseSpUtils.getInstance().setCircleStatus(mActivity, 1);

    }

    @Override
    public void noAddCircle(int code) {
        if (code == 404) {
            circleMessageBtn.setVisibility(View.VISIBLE);
            circleMessageBtn.setText("加入圈子");
            BaseSpUtils.getInstance().setCircleStatus(mActivity, 0);
        } else {
            circleMessageBtn.setVisibility(View.GONE);
        }

    }

    @Override
    public void setNeighborMsgData(CircleMessageBean entity) {
        loadService.showSuccess();
        //圈子名称
        circleName = entity.getCircleName();
        circleMessageName.setText(circleName);
        //地址
        circleMessageAddress.setText(entity.getAddress());
        //距离
        float dis = RxDataTool.stringToFloat(entity.getDistance());
        if (dis < 1000) {
            String dis1 = RxDataTool.getRoundUp(dis + "", 0);
            circleMessageDistance.setText(dis1 + "m");
        } else {
            String dis1 = RxDataTool.getRoundUp(dis / 1000 + "", 0);
            circleMessageDistance.setText(dis1 + "km");
        }
        //圈子人数
        circlePersons = entity.getUserNum();
        circleMessageUser.setText(circlePersons + "位");

        if (null != entity.getBlogImages() && entity.getBlogImages().size() > 0) {

            if (entity.getBlogImages().size() == 1) {
                if (!RxDataTool.isNullString(entity.getBlogImages().get(0))) {
                    circleMessageDynamicIv1.setVisibility(View.VISIBLE);
                    GlideApp.with(mActivity)
                            .load(entity.getBlogImages().get(0))
                            .placeholder(R.mipmap.image_default)
                            .error(R.mipmap.image_default)
                            .into(circleMessageDynamicIv1);
                } else {
                    circleMessageDynamicIv1.setVisibility(View.INVISIBLE);
                }
            } else if (entity.getBlogImages().size() == 2) {
                if (!RxDataTool.isNullString(entity.getBlogImages().get(0))) {
                    circleMessageDynamicIv1.setVisibility(View.VISIBLE);
                    GlideApp.with(mActivity)
                            .load(entity.getBlogImages().get(0))
                            .placeholder(R.mipmap.image_default)
                            .error(R.mipmap.image_default)
                            .into(circleMessageDynamicIv1);
                } else {
                    circleMessageDynamicIv1.setVisibility(View.INVISIBLE);
                }

                if (!RxDataTool.isNullString(entity.getBlogImages().get(1))) {
                    circleMessageDynamicIv2.setVisibility(View.VISIBLE);
                    GlideApp.with(mActivity)
                            .load(entity.getBlogImages().get(1))
                            .placeholder(R.mipmap.image_default)
                            .error(R.mipmap.image_default)
                            .into(circleMessageDynamicIv2);
                } else {
                    circleMessageDynamicIv2.setVisibility(View.INVISIBLE);
                }
            } else if (entity.getBlogImages().size() >= 3) {
                if (!RxDataTool.isNullString(entity.getBlogImages().get(0))) {
                    circleMessageDynamicIv1.setVisibility(View.VISIBLE);
                    GlideApp.with(mActivity)
                            .load(entity.getBlogImages().get(0))
                            .placeholder(R.mipmap.image_default)
                            .error(R.mipmap.image_default)
                            .into(circleMessageDynamicIv1);
                } else {
                    circleMessageDynamicIv1.setVisibility(View.INVISIBLE);
                }

                if (!RxDataTool.isNullString(entity.getBlogImages().get(1))) {
                    circleMessageDynamicIv2.setVisibility(View.VISIBLE);
                    GlideApp.with(mActivity)
                            .load(entity.getBlogImages().get(1))
                            .placeholder(R.mipmap.image_default)
                            .error(R.mipmap.image_default)
                            .into(circleMessageDynamicIv2);
                } else {
                    circleMessageDynamicIv2.setVisibility(View.INVISIBLE);
                }

                if (!RxDataTool.isNullString(entity.getBlogImages().get(2))) {
                    circleMessageDynamicIv3.setVisibility(View.VISIBLE);
                    GlideApp.with(mActivity)
                            .load(entity.getBlogImages().get(2))
                            .placeholder(R.mipmap.image_default)
                            .error(R.mipmap.image_default)
                            .into(circleMessageDynamicIv3);
                } else {
                    circleMessageDynamicIv3.setVisibility(View.INVISIBLE);
                }
            }
        }

    }

    @Override
    public void addNeighborSuccess() {
        showNormal("加入圈子成功");

        BaseSpUtils.getInstance().setCircleStatus(mActivity, 1);

        hasCircle = BaseSpUtils.getInstance().getCircleStatus(mActivity);

        if (hasCircle == 1) {
            circleMessageBtn.setText("退出圈子");
        } else if (hasCircle == 0) {
            //异常情况
            circleMessageBtn.setText("加入圈子");
        }

        EventBus.getDefault().post(new AppEvent(EventConfig.REFRESH_NEAR_CIRCLE));
//        EventBus.getDefault().post(new AppEvent(EventConfig.REFRESH_HOME_MAIN_FRAGMENT_CIRCLE));

    }

    @Override
    public void addNeighborFail(String s) {
        showNormal("加入圈子失败");

    }

    @Override
    public void quitNeighborSuccess() {
        showNormal("退出圈子成功");

        BaseSpUtils.getInstance().setCircleStatus(mActivity, 0);

        hasCircle = BaseSpUtils.getInstance().getCircleStatus(mActivity);

        if (hasCircle == 0) {
            circleMessageBtn.setText("加入圈子");
        } else if (hasCircle == 1) {
            //异常情况
            circleMessageBtn.setText("退出圈子");
        }

        EventBus.getDefault().post(new AppEvent(EventConfig.REFRESH_NEAR_CIRCLE));
        EventBus.getDefault().post(new AppEvent(EventConfig.REFRESH_MINE_CIRCLE, 0));

    }

    @Override
    public void quitNeighborFail(String s) {
        showNormal("退出圈子失败");

    }

    @Override
    public void showError(String s) {
        loadService.showCallback(ErrorCallback.class);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R2.id.circle_message_back)
    public void backClick(View view) {
        finish();
    }

    @OnClick(R2.id.circle_message_user_rl)
    public void userClick(View view) {
        //圈子用户
        Intent intent = new Intent(mActivity, NeighborPersonsActivity.class);
        intent.putExtra("circle_id", circleId);
        intent.putExtra("circle_name", circleName);
        intent.putExtra("circle_persons", circlePersons);
        startActivity(intent);
    }

    @OnClick(R2.id.circle_message_dynamic_rl)
    public void circleClick(View view) {
        //
        Intent intent = new Intent(mActivity, NeighborCircleActivity.class);
        intent.putExtra("circle_id", circleId);
        startActivity(intent);
    }

}
